package warehouseArea

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"gorm.io/gorm"
	"insighttracking/apps/admin/auth"
	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"
	types2 "insighttracking/common/types"
	"insighttracking/common/utils"
	"insighttracking/query/bo"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type ApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *ApiLogic {
	hostname, _ := os.Hostname()
	return &ApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *ApiLogic) CreateApi(req *types.CreateWareHouseAreaReq) (resp string, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}

	_, err = service.WarehouseService.GetWarehouseByIdApi(l.ctx, accountInfo.EnterpriseId, req.WarehouseID)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return "", errors.New("仓库ID有误")
	}

	var isDefault int64
	if req.IsDefault == 0 {
		_, err = service.WarehouseAreaService.GetByEnterpriseIdApi(l.ctx, accountInfo.EnterpriseId, req.WarehouseID)
		if errors.Is(err, gorm.ErrRecordNotFound) {
			isDefault = 1
		}
	} else {
		isDefault = 1
		err = service.WarehouseAreaService.SetAllDefaultApi(l.ctx, accountInfo.EnterpriseId, req.WarehouseID)
		if err != nil {
			return "", err
		}
	}

	if req.Code == "" {
		var count int64
		count, err = service.WarehouseAreaService.GetCountByWareHouseIdApi(l.ctx, accountInfo.EnterpriseId, req.WarehouseID)
		req.Code = "KQ" + fmt.Sprintf("%04d", count+1)
	}

	if err = service.WarehouseAreaService.CreateApi(l.ctx, model.WarehouseAreaEntity{
		Name:         req.Name,     // 仓库名称
		Code:         req.Code,     // 仓库编码
		IsDefault:    isDefault,    // 是否为默认仓库,0表示不是，1表示是
		Status:       req.Status,   // 状态 0-正常 1-禁用
		Describe:     req.Describe, // 仓库名称描述
		EnterpriseID: accountInfo.EnterpriseId,
		WarehouseID:  req.WarehouseID,
	}); err != nil {
		return "", errors.New(err.Error())
	}
	return "操作成功", nil
}

func (l *ApiLogic) DeleteByIdApi(req *types.IdReq) (resp string, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}
	// TODO 判断不能删除的情况

	if err = service.WarehouseAreaService.DeleteByIdApi(l.ctx, accountInfo.EnterpriseId, req.Id); err != nil {
		return "", err
	}
	return "操作成功", nil
}

func (l *ApiLogic) GetListApi(warehouseId int64) (resp []types2.SimpleList, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return make([]types2.SimpleList, 0), nil
	}
	warehouseList, err := service.WarehouseAreaService.GetListApi(l.ctx, accountInfo.EnterpriseId, warehouseId)
	if err != nil {
		return make([]types2.SimpleList, 0), nil
	}
	return k.Map(warehouseList, func(item *model.WarehouseAreaEntity, index int) types2.SimpleList {
		return types2.SimpleList{
			ID:   item.ID,   // 主键id
			Name: item.Name, // 仓库名称
			Code: item.Code, // 仓库编码
		}
	}), nil
}

func (l *ApiLogic) GetPageApi(req *types.WarehouseAreaPageReq) (resp *types.WarehouseAreaPageResp, err error) {
	resp = &types.WarehouseAreaPageResp{
		PageBaseResp: types.PageBaseResp{
			Total:      0,
			PageSize:   req.PageSize,
			PageNumber: req.PageNumber,
		},
		Data: make([]types.WarehouseAreaModel, 0), // 表格数据
	}
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return
	}

	warehouseAreaBo, count, err := service.WarehouseAreaService.GetPageApi(l.ctx, bo.WarehouseAreaPageReqBo{
		WareHouseId:  req.WarehouseId, //仓库ID
		PageSize:     req.PageSize,    // 当前条数
		PageNumber:   req.PageNumber,  // 当前页数
		Name:         req.Name,        // 仓库名称或者编码
		Status:       req.Status,      // 仓库状态
		EnterpriseId: accountInfo.EnterpriseId,
	})

	if err != nil {
		return
	}

	warehouseResp := k.Map(warehouseAreaBo, func(item bo.WarehouseAreaPageRespBo, index int) types.WarehouseAreaModel {
		return types.WarehouseAreaModel{
			ID:            item.ID,                                 // 主键id
			Name:          item.Name,                               // 库区名称
			WarehouseName: item.WarehouseName,                      // 仓库名称
			Code:          item.Code,                               // 仓库编码
			Status:        item.Status,                             // 状态0表示正常,1表示禁用
			IsDefault:     item.IsDefault,                          // 是否为默认仓库,0表示不是，1表示是
			Describe:      item.Describe,                           // 仓库名称描述
			CreatedAt:     utils.TimestampToString(item.CreatedAt), // 创建时间
			UpdatedAt:     utils.TimestampToString(item.UpdatedAt),
		}
	})

	return &types.WarehouseAreaPageResp{
		PageBaseResp: types.PageBaseResp{
			Total:      count,
			PageSize:   req.PageSize,
			PageNumber: req.PageNumber,
		},
		Data: warehouseResp, // 表格数据
	}, nil
}

func (l *ApiLogic) ModifyByIdApi(req *types.ModifyWarehouseAreaReq) (resp string, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}

	if err = service.WarehouseAreaService.ModifyByIdApi(l.ctx, req.Id, accountInfo.EnterpriseId, bo.CreateWarehouseBo{
		Name:     req.Name,     // 仓库名称
		Code:     req.Code,     // 仓库编码
		Describe: req.Describe, // 仓库名称描述
	}); err != nil {
		return "", err
	}
	return "操作成功", nil
}

func (l *ApiLogic) ModifyDefaultByIdApi(req *types.IdReq) (resp string, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}
	if err = service.WarehouseAreaService.ModifyDefaultByIdApi(l.ctx, accountInfo.EnterpriseId, req.Id); err != nil {
		return "", err
	}
	return "操作成功", nil
}

func (l *ApiLogic) ModifyStatusByIdApi(req *types.IdReq) (resp string, err error) {
	if err = service.WarehouseAreaService.ModifyStatusByIdApi(l.ctx, req.Id); err != nil {
		return "", err
	}
	return "操作成功", nil
}
